/**
 * Copyright (C) 2010 Neofonie GmbH
 *
 * This programm is free software; you can redistribute it and/or modify
 * it under the terms of the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package eu.dicode.analysis.demonstrator;

import eu.dicode.analysis.demonstrator.util.Configuration;
import eu.dicode.analysis.demonstrator.util.FileSystemScanner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import sun.util.LocaleServiceProviderPool;

import java.io.*;
import java.util.Hashtable;

/**
 * Reads a dumped sequencefile containing the results of our histogram analysis and returns the results per
 * query as json formatted string.
 */
@Controller
public class HistogramDataController {
  private static final Logger LOG = LoggerFactory.getLogger(HistogramDataController.class);
  private final String histogramRawData;
  private final FileSystemScanner scanner;

  /**
   * Package private - here for testing only.
   * */
  HistogramDataController(final String histogramLocation) {
    this.histogramRawData = histogramLocation;
    this.scanner = new FileSystemScanner();
  }

  public HistogramDataController() {
    Configuration config = Configuration.getInstance();
    String location = config.getStringValue(
        Configuration.DICODE_HISTOGRAM_LOCATION,
        Configuration.DICODE_DEFAULT_HISTOGRAM_LOCATION);

    this.histogramRawData = location;
    this.scanner = new FileSystemScanner();
  }

  @RequestMapping(value="/data/hist/{queryString}.hist", method = RequestMethod.GET)
  public void data(@PathVariable String queryString, final Model model, final Writer responseWriter) throws IOException, FileNotFoundException {
    // Find the directory on disk that holds our histogram
    File histogramFile = this.scanner.getFile(queryString, this.histogramRawData);

    BufferedReader reader = new BufferedReader(new FileReader(histogramFile));
    String line = reader.readLine();
    StringBuffer result = new StringBuffer("[[");
    while (line != null) {
      if (line.startsWith("Key: [")) {
        String[] entries = line.split(" ");
        String x = entries[2].substring(0, entries[2].length() - 2);
        String y = entries[4];
        if (result.length() > 2) {
          result.append(", ");
        }
        result.append("[").append(x).append(", ").append(y).append("]");
      }
      line = reader.readLine();
    }
    if (result.length() == 2) result.append("[10350, 1]");
    result.append("]]");
    responseWriter.write(result.toString());
  }
}
